package models
import(
	"encoding/json"
	"net/http"
	"io/ioutil"
	"strings"
	"strconv"
)
//DateWeather  每天的天气状况
type DateWeather struct
{
	Date string
	High string 
	Low string
	Fx string
	Fl string 
	Type string
	Notice string
	Quality string  //空气质量 
}

type weatherData struct
{
	Shidu string
	Pm25 float32
	Pm10 float32
	Quality string 
	Forecast []DateWeather
}

type weatherInfo struct
{
	Date string
	Message string
	Status int
	City string
	Count int
	Data weatherData
}

type WeaterError struct {
	msg    string // description of error
	Offset int64  // error occurred after reading Offset bytes
}
func (e *WeaterError) Error() string { return e.msg }

//IsRightForOut 判断天气是否适合出门  0 不适合  1不建议  2 天气不错可以出门
func IsRightForOut(wa DateWeather )(int,string) {
	str:=strings.Replace(wa.High,"高温 ","",-1)
	str=strings.Replace(str,"℃","",-1)
	high,_:= strconv.ParseFloat(str,32)

	str=strings.Replace(wa.Low,"低温 ","",-1)
	str=strings.Replace(str,"℃","",-1)
	low,_:= strconv.ParseFloat(str,32)
	if(low<0){
		//最低气温小于0度 或者最高温度超过30度 
		return 0,"室外气温低于0度，不宜外出就餐"
	}
	if(high>30){
		//最低气温小于0度 或者最高温度超过30度 
		return 0,"室外气温高于30度，不宜外出就餐"
	}
	if strings.Contains(wa.Type,"雨")|| strings.Contains(wa.Type,"雪") {
		// 雨雪天气
		return 0,"雨雪天气，不宜出门"
	}
	if wa.Quality!="良"&&wa.Quality!="优" {
		//空气质量差的
		return 0,"空气质量差，不宜外出就餐"
	}
    if(low<10){
		//最低温度 0~10 最高温度 25~30 的
		return 1,"气温偏低，不建议外出就餐"
	}
	if high>25 {
		return 1,"气温偏高，不建议外出就餐"
	}
	if(wa.Quality!="良"){
		//空气质量良
		return 1,"空气质量良"
	}
	return 2,"惠风和畅吗,气温舒适,适宜外出就餐"
}

//GetWeather 获取天气状况
func GetWeather(cityname string ) (DateWeather,bool) {
	var wa weatherInfo
	waurl := "https://www.sojson.com/open/api/weather/json.shtml?city="+cityname
	strWeather := HTTPGet(waurl)
	//fmt.Println(strWeather)
	err := json.Unmarshal([]byte(strWeather), &wa)
	if err!=nil {
        //fmt.Println("Can't decode weather json message",err)
	}
	forecast:=wa.Data.Forecast
	var  tody DateWeather
	if len(forecast)>0{
		tody =wa.Data.Forecast[0]
		tody.Quality = wa.Data.Quality
		return tody,true
	
	}
	return tody,false
	//fmt.Println("wa",wa.Data.Forecast[0])
}

//HTTPGet http get
func HTTPGet(url string) string {
	response,err := http.Get(url)
	if err != nil {
		// handle error
	}
    defer response.Body.Close()
    body,err := ioutil.ReadAll(response.Body)
	if err != nil {
		// handle error
	}
	//fmt.Println()
	return string(body)
}


